using AutoBackupSql.Models;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using Microsoft.Extensions.Options;

namespace AutoBackupSql.Services
{
    public class MySqlBackupService
    {
        private readonly ILogger<MySqlBackupService> _logger;
        private readonly BackupSettings _settings;

        public MySqlBackupService(ILogger<MySqlBackupService> logger, IOptions<BackupSettings> options)
        {
            _logger = logger;
            _settings = options.Value;
        }

        public async Task<string> CreateBackupAsync()
        {
            var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            var backupFileName = $"backup_{_settings.SourceDatabase.Database}_{timestamp}.sql";
            var backupFilePath = Path.Combine(_settings.LocalBackupPath, backupFileName);

            try
            {
                // 确保备份目录存在
                Directory.CreateDirectory(_settings.LocalBackupPath);

                // 构建mysqldump命令
                var mysqldumpArgs = $"--host={_settings.SourceDatabase.Server} " +
                                   $"--port={_settings.SourceDatabase.Port} " +
                                   $"--user={_settings.SourceDatabase.Username} " +
                                   $"--password={_settings.SourceDatabase.Password} " +
                                   $"--single-transaction " +
                                   $"--routines " +
                                   $"--triggers " +
                                   $"--events " +
                                   $"--databases {_settings.SourceDatabase.Database} " +
                                   $"--result-file=\"{backupFilePath}\"";

                _logger.LogInformation("开始创建MySQL备份: {BackupFile}", backupFileName);

                // 执行mysqldump命令
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "mysqldump",
                        Arguments = mysqldumpArgs,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true
                    }
                };

                process.Start();
                await process.WaitForExitAsync();

                if (process.ExitCode == 0)
                {
                    var fileInfo = new FileInfo(backupFilePath);
                    _logger.LogInformation("MySQL备份创建成功: {BackupFile}, 大小: {Size} MB", 
                        backupFileName, Math.Round(fileInfo.Length / 1024.0 / 1024.0, 2));
                    return backupFilePath;
                }
                else
                {
                    var error = await process.StandardError.ReadToEndAsync();
                    throw new Exception($"mysqldump执行失败: {error}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建MySQL备份失败: {BackupFile}", backupFileName);
                throw;
            }
        }

        public async Task<bool> TestConnectionAsync()
        {
            try
            {
                using var connection = new MySqlConnection(_settings.SourceDatabase.GetConnectionString());
                await connection.OpenAsync();
                _logger.LogInformation("MySQL连接测试成功");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "MySQL连接测试失败");
                return false;
            }
        }

        public void CleanupOldBackups()
        {
            try
            {
                var cutoffDate = DateTime.Now.AddDays(-_settings.BackupSchedule.RetentionDays);
                var backupFiles = Directory.GetFiles(_settings.LocalBackupPath, "backup_*.sql");

                foreach (var file in backupFiles)
                {
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.CreationTime < cutoffDate)
                    {
                        File.Delete(file);
                        _logger.LogInformation("删除过期备份文件: {File}", fileInfo.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理过期备份文件失败");
            }
        }
    }
} 